<?php
namespace app\api\controller;

use app\common\controller\Base;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use app\common\model\server\Setting;
class Email extends Base
{
    protected $mail;
    public function initialize(){
        
    }
    public function __construct()
    {
        $currentConfig = Setting::detail()->toArray();
        $emailconfig=json_decode($currentConfig['email_config'],true);
        $this->mail = new PHPMailer(true);
        $this->mail->isSMTP();
        $this->mail->CharSet = 'utf-8';
        $this->mail->Host = $emailconfig['mail_smtp_host']; // SMTP服务器地址
        $this->mail->SMTPAuth = true;
        $this->mail->Username = $emailconfig['mail_smtp_user']; // 邮箱用户名
        $this->mail->Password = $emailconfig['mail_smtp_pass']; // 邮箱密码
        $this->mail->SMTPSecure = $emailconfig['mail_verify_type']==1 ? 'SSL' : 'TLS';// 启用SSL加密
        $this->mail->Port = $emailconfig['mail_smtp_port']; // SMTP端口
        $this->mail->From=$emailconfig['mail_from']; // SMTP端口
    }
 
    public function sendEmail($to, $subject, $body)
    {
        $this->mail->setFrom($this->mail->From, $this->mail->From); // 发件人
        $this->mail->addAddress($to);     // 添加接收者
        $this->mail->isHTML(true);        // 支持HTML格式
        $this->mail->Subject = $subject;  // 邮件标题
        $this->mail->Body    = $body;     // 邮件内容
 
        try {
            $this->mail->send();
            return true;
        } catch (Exception $e) {
            echo "Message could not be sent. Mailer Error: {$this->mail->ErrorInfo}";
            return false;
        }
    }
}